package com.x86.util;


import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传工具类
 * @author 风亦未止
 * @date 2021/9/1 20:37
 */
public class FileUploadUtil {
    /**
     * 上传文件工具类
     * @param uploadFile 文件
     * @param request
     * @return
     */
    public static String uploadUtil(MultipartFile uploadFile, HttpServletRequest request) {
        //项目的部署目录 + img/product/image/
        String savePath = request.getServletContext().getRealPath("/resource/file/");
        //处理随机文件名
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + FilenameUtils.getExtension(uploadFile.getOriginalFilename());
        //上传目录如果不存在,先创建
        File savePathDir = new File(savePath);
        if (!savePathDir.exists()) {
            savePathDir.mkdirs();
        }
        //保存文件
        try {
            uploadFile.transferTo(new File(savePathDir, fileName));
        } catch (IOException e) {
            return null;
        }
        String url="/resource/file/"+fileName;
        return url;
    }
}
